/**
 * CopyRright @2014 SIM TECHNOLOGY ALL RIGHTS RESERVED
 * @Title: RestResponse.java
 * @Package cm.sim.com.core.rest
 * @Description: TODO
 * @author he.sun 
 * @date 2015年3月18日 下午12:14:33
 * @version V1.0
 */

package guoan.Exception;

import guoan.core.dto.RestResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.google.gson.Gson;

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    private Gson gson = new Gson();

    @Autowired
    private MessageSource messageSource;

    /**
     * 处理Exception.
     */
    @ExceptionHandler(value = { RestException.class, IllegalArgumentException.class, NullPointerException.class, IndexOutOfBoundsException.class })
    public final ResponseEntity<Object> handleException(RuntimeException ex, WebRequest request){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String body = gson.toJson(RestResponse.error(ex.getMessage()));
        return new ResponseEntity<Object>(body, HttpStatus.OK);
    }
}
